package com.mifengs.mall.ui.login;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.mifengs.commonbase.util.ToastUitl;
import com.mifengs.mall.Constant;
import com.mifengs.mall.R;
import com.mifengs.commonbase.base.BaseActivity;
import com.mifengs.mall.di.component.DaggerRegisterComponent;
import com.mifengs.mall.di.module.RegisterModule;
import com.mifengs.mall.ui.web.CommonWebActivity;
import com.mifengs.mall.util.PwdCheckUtil;
import com.mifengs.mall.util.Tools;
import com.mifengs.mall.widget.VerifyCodeView;
import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class NewRegisterActivity extends BaseActivity<RegisterPresent> implements RegisterContract.View {


    @BindView(R.id.et_iphone)
    EditText etIphone;
    @BindView(R.id.et_password)
    EditText etPassword;
    @BindView(R.id.password_img)
    ImageView passwordImg;
    @BindView(R.id.et_verity_code)
    EditText etVerityCode;
    @BindView(R.id.input_code)
    EditText inputCode;
    @BindView(R.id.code_btn)
    Button codeBtn;
    @BindView(R.id.code_time)
    TextView codeTime;
    @BindView(R.id.rlayout_code)
    RelativeLayout rlayoutCode;
    @BindView(R.id.checkbox)
    CheckBox checkbox;
    @BindView(R.id.btn_register)
    Button btnRegister;
    @BindView(R.id.tx_share)
    TextView txShare;
    @BindView(R.id.btn_agreement)
    TextView txAgreement;
    @BindView(R.id.contact_im)
    TextView contactIm;
    @BindView(R.id.error_tet)
    TextView errorTet;
    @BindView(R.id.llayout_toast)
    LinearLayout llayoutToast;
    @BindView(R.id.relative_phone_del)
    RelativeLayout relativePhoneDel;
    @BindView(R.id.btn_photo_code)
    VerifyCodeView mPhotoCodeWebView;
    private MyTime myTime;
    private boolean isCheckbox = true;
    private boolean isPhone = true;
    private String mShareId;
    private boolean mDisplayFlg = false;
    private ShowErrorThread errorThread;
    private Dialog imDilaog;

    Handler mHandle = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    if(llayoutToast != null){
                        llayoutToast.setVisibility(View.GONE);
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_register);
        ButterKnife.bind(this);
        setStatusColorAndMode(R.color.white, true);
        init();
    }

    private void init() {
        initNavigationBar();
        mShareId = getIntent().getStringExtra("shareId");
        if (!TextUtils.isEmpty(mShareId)) {
            txShare.setVisibility(View.VISIBLE);
            txShare.setText("分享码" + " " + mShareId);
        }
        myTime = new MyTime(60000, 1000);
        checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    isCheckbox = true;
                } else {
                    isCheckbox = false;
                }
            }
        });
        txAgreement.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        contactIm.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        etIphone.addTextChangedListener(textWatcher);
        etVerityCode.addTextChangedListener(textWatcher);
        inputCode.addTextChangedListener(textWatcher);
        etPassword.addTextChangedListener(textWatcher);
        btnRegister.setClickable(false);
        mPhotoCodeWebView.loadUrl(Constant.PHONE_CODE);
        mPhotoCodeWebView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                mPhotoCodeWebView.reload();
                return false;
            }
        });
    }

    @Override
    public void initInjector() {
        DaggerRegisterComponent.builder()
                .registerModule(new RegisterModule(this))
                .build()
                .inject(this);
    }

    @Override
    public boolean isVerification() {
        String phone = getPhone();
        String pwd = getPwd();
        String code = getCode();
        String photoCode = getPhotoCode();
        if ("".equals(phone)) {
            setErrorInfo("请输入手机号码");
            return false;
        } else if (phone.length() != 11) {
            setErrorInfo("手机号码输入错误");
            return false;
        } else if ("".equals(code)) {
            setErrorInfo("请输入验证码");
            return false;
        } else if ("".equals(photoCode)) {
            setErrorInfo("请输入图形码");
            return false;
        } else if ("".equals(pwd)) {
            setErrorInfo("请输入密码");
            return false;
        } else if (pwd.length() < 6) {
            setErrorInfo("密码的长度为6-16位");
            return false;
        } else if (pwd.length() > 16) {
            setErrorInfo("密码的长度为6-16位");
            return false;
        } else if (!PwdCheckUtil.isContainAll(pwd)) {
            setErrorInfo("必须同时包含字母+数字的组合");
            return false;
        }

        return true;
    }

    @Override
    public boolean isVerificationPhone() {
        String phone = getPhone();
        String phoneCode = getPhotoCode();
        if ("".equals(phone)) {
            setErrorInfo("请输入手机号码");
            return false;
        } else if (phone.length() != 11) {
            setErrorInfo("手机号码输入错误");
            return false;
        } else if ("".equals(phoneCode)) {
            setErrorInfo("请输入图形验证码");
            return false;
        } else if (!Tools.checkCellphone(phone)) {
            setErrorInfo("请输入正确手机号码");
            return false;
        }
        return true;
    }

    private void setErrorInfo(String errorInfo) {
        llayoutToast.setVisibility(View.VISIBLE);
        errorTet.setText(errorInfo);
        errorThread = new ShowErrorThread();
        errorThread.start();

    }


    public class ShowErrorThread extends Thread {
        @Override
        public void run() {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Message msg = new Message();
            msg.what = 1;
            mHandle.sendMessage(msg);
        }
    }

    @Override
    public String getPwd() {
        return etPassword.getText().toString();
    }

    @Override
    public String getPhone() {
        return etIphone.getText().toString();
    }

    @Override
    public String getCode() {
        return inputCode.getText().toString();
    }

    @Override
    public String getPhotoCode() {
        return etVerityCode.getText().toString();
    }

    @Override
    public String getShareId() {
        return mShareId;
    }

    @Override
    public void isPhone() {
        myTime.start();
        codeBtn.setVisibility(View.GONE);
        rlayoutCode.setVisibility(View.VISIBLE);
    }

    @Override
    public void toSuccess() {

    }

    class MyTime extends CountDownTimer {

        public MyTime(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            Date date = new Date(millisUntilFinished);
            SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
            String str = sdf.format(date);
//            System.out.println(str);
            codeTime.setText("(" + millisUntilFinished / 1000 + "s" + ")");
        }

        @Override
        public void onFinish() {
            rlayoutCode.setVisibility(View.GONE);
            codeBtn.setVisibility(View.VISIBLE);
        }
    }


    private void passwordTransformation() {

        if (!mDisplayFlg) {
            // display password text, for example "123456"
            etPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            // hide password, display "."
            etPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }

        mDisplayFlg = !mDisplayFlg;

        etPassword.postInvalidate();

        if (mDisplayFlg) {
            passwordImg.setImageResource(R.drawable.ic_input_xianshi);
        } else {
            passwordImg.setImageResource(R.drawable.ic_input_noxianshi);
        }

    }


    protected void initNavigationBar() {
        RelativeLayout llNavBar = (RelativeLayout) this.findViewById(R.id.navigation_bar);
        if (llNavBar != null) {
            LinearLayout llBack = (LinearLayout) this.findViewById(R.id.ll_back);
            llBack.setVisibility(View.VISIBLE);
            TextView titleText = (TextView) this.findViewById(R.id.tv_title);
            titleText.setVisibility(View.VISIBLE);
            titleText.setText("免费注册");
            llBack.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    finish();
                }
            });
        }
    }

    @OnClick({R.id.password_img, R.id.code_btn, R.id.btn_agreement, R.id.btn_register, R.id.contact_im, R.id.ll_back,R.id.relative_phone_del})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.password_img://秘密显示与加密
                passwordTransformation();
                break;
            case R.id.ll_back:
                finish();
                break;
            case R.id.code_btn:
                if (isVerificationPhone())
                    if (codeBtn.getText().toString().equals(getResources().getString(R.string.send_code))) {
                        mPresenter.isPhone();
                    }

                break;
            case R.id.btn_register:
                if (isVerification()) {
                    if (isCheckbox) {
                        mPresenter.register();
                    } else {
                        ToastUitl.show("请勾选使用协议", Toast.LENGTH_SHORT);
                    }
                }
                break;
            case R.id.btn_agreement:
                intent = new Intent(getContext(), CommonWebActivity.class);
                intent.putExtra("ExtraWebPath", "https://www.mifengs.com/mifengs_m/agreementoverlay");
                intent.putExtra("ExtraWebTitle", "网络服务和使用协议");
                startActivity(intent);
                break;
            case R.id.contact_im:
                showImDialog();
                break;
            case R.id.relative_phone_del:
                etIphone.setText("");
                relativePhoneDel.setVisibility(View.GONE);
                break;
        }
    }


    TextWatcher textWatcher= new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String phone = getPhone();
            String photoCode = getPhotoCode();
            String code = getCode();
            String pwd = getPwd();
            if (TextUtils.isEmpty(pwd) || TextUtils.isEmpty(phone) || TextUtils.isEmpty(photoCode) || TextUtils.isEmpty(code) || TextUtils.isEmpty(s)) {
                btnRegister.setBackgroundResource(R.drawable.btn_not_select);
                btnRegister.setClickable(false);
            } else {
                btnRegister.setBackgroundResource(R.drawable.btn_select);
                btnRegister.setClickable(true);

            }
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (TextUtils.isEmpty(s.toString())) {
                relativePhoneDel.setVisibility(View.INVISIBLE);
            } else {
                relativePhoneDel.setVisibility(View.VISIBLE);
            }
        }
    };


    private void showImDialog() {
        imDilaog = new Dialog(this, R.style.dialog);
        imDilaog.setContentView(R.layout.dialog_update);
        imDilaog.show();
        TextView tvTile = (TextView) imDilaog.findViewById(R.id.textView1);
        tvTile.setText("联系客服");
        TextView tvContent = (TextView) imDilaog.findViewById(R.id.tv_update_info);
        tvContent.setText("您是需要拨打tel:400-9683889 客服电话吗");
        Button okBtn = imDilaog.findViewById(R.id.bt_update);
        okBtn.setText("去拨打");
        okBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("tel:400-9683889"));
                startActivity(intent);
            }
        });
        Button cancleBtn = imDilaog.findViewById(R.id.bt_cancle);
        cancleBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imDilaog.dismiss();

            }
        });
    }

        @Override
    protected void onDestroy() {
        super.onDestroy();
        if (errorThread != null) {
            if (errorThread.isAlive()) {
                errorThread.interrupt();
            }
        }
            if (myTime != null) {
                myTime.cancel();
            }
    }

}
